const app = getApp();

Page({
  data: {
    isLogin: false,
    cartList: [],
    recommendProducts: [],
    allSelected: false,
    totalPrice: 0,
    selectedCount: 0
  },

  onLoad: function () {
    this.checkLoginStatus();
  },

  onShow: function () {
    this.checkLoginStatus();
    if (this.data.isLogin) {
      this.getCartList();
      this.getRecommendProducts();
    }
  },

  // 检查登录状态
  checkLoginStatus: function () {
    const isLogin = app.globalData.isLogin;
    this.setData({
      isLogin
    });
  },

  // 获取购物车列表
  getCartList: function () {
    // 从本地存储获取购物车数据
    let cartList = wx.getStorageSync('cart') || [];
    
    console.log('从本地存储获取购物车数据:', cartList);
    
    // 同步到全局变量（确保全局状态与本地存储一致）
    app.globalData.cartList = cartList;
    
    this.setData({
      cartList: cartList,
      isEmpty: cartList.length === 0
    });
    
    // 计算总金额和选择状态
    this.calculateTotal();
  },

  // 获取推荐商品
  getRecommendProducts: function () {
    // 实际项目中应该从服务器获取推荐商品
    // wx.cloud.callFunction({
    //   name: 'getRecommendProducts',
    //   data: {
    //     userId: app.globalData.userInfo._id,
    //     limit: 10
    //   }
    // }).then(res => {
    //   if (res.result.success) {
    //     const recommendProducts = res.result.data;
    //     this.setData({
    //       recommendProducts
    //     });
    //   }
    // }).catch(err => {
    //   console.error('获取推荐商品失败', err);
    // });

    // 使用模拟数据
    setTimeout(() => {
      // 检查是否已经有推荐商品数据，避免重复添加
      if (this.data.recommendProducts && this.data.recommendProducts.length > 0) {
        return;
      }
      
      const recommendProducts = [
        {
          id: 1003,
          name: '牛仔裤',
          price: 159,
          imageUrl: 'https://img01.yzcdn.cn/vant/cat.jpeg'
        },
        {
          id: 1004,
          name: '运动鞋',
          price: 299,
          imageUrl: 'https://img01.yzcdn.cn/vant/cat.jpeg'
        },
        {
          id: 1005,
          name: '时尚包包',
          price: 259,
          imageUrl: 'https://img01.yzcdn.cn/vant/cat.jpeg'
        }
      ];
      this.setData({
        recommendProducts
      });
    }, 500);
  },

  // 计算总价和选中数量
  calculateTotal: function () {
    let cartList = this.data.cartList;
    let totalPrice = 0;
    let selectedCount = 0;
    let allSelected = cartList.length > 0;

    cartList.forEach(item => {
      if (item.selected) {
        totalPrice += item.price * item.quantity;
        selectedCount += item.quantity;
      } else {
        allSelected = false;
      }
    });

    totalPrice = parseFloat(totalPrice.toFixed(2));

    this.setData({
      totalPrice: totalPrice,
      selectedCount: selectedCount,
      allSelected: allSelected
    });

    // 将选中的商品保存到全局变量，用于结算页面
    let checkoutItems = cartList.filter(item => item.selected).map(item => {
      return {
        id: item.id,
        name: item.name,
        price: item.price,
        quantity: item.quantity,
        image: item.image,
        selected: true
      };
    });
    
    // 保存到全局变量和本地存储
    if (getApp().globalData) {
      getApp().globalData.checkoutItems = checkoutItems;
    }
    wx.setStorageSync('checkoutItems', checkoutItems);
    console.log('已保存结算商品:', checkoutItems);
  },

  // 切换全选状态
  toggleSelectAll: function () {
    let cartList = this.data.cartList;
    let allSelected = !this.data.allSelected;

    cartList.forEach(item => {
      item.selected = allSelected;
    });

    this.setData({
      cartList: cartList,
      allSelected: allSelected
    });

    this.calculateTotal();
    
    // 更新本地存储
    wx.setStorageSync('cart', cartList);
  },
  
  // 切换单个商品选中状态
  toggleSelect: function (e) {
    const index = e.currentTarget.dataset.index;
    let cartList = this.data.cartList;
    cartList[index].selected = !cartList[index].selected;

    this.setData({
      cartList: cartList
    });

    this.calculateTotal();
    
    // 更新本地存储
    wx.setStorageSync('cart', cartList);
  },

  // 增加商品数量
  increaseCount: function (e) {
    const { index } = e.currentTarget.dataset;
    const { cartList } = this.data;
    
    // 增加数量上限判断
    if (cartList[index].quantity < 99) {
      cartList[index].quantity += 1;
      
      this.setData({
        cartList
      });
      
      this.calculateTotal();
      this.updateCartToGlobal();
    } else {
      wx.showToast({
        title: '已达到最大购买数量',
        icon: 'none'
      });
    }
  },
  
  // 减少商品数量
  decreaseCount: function (e) {
    const { index } = e.currentTarget.dataset;
    const { cartList } = this.data;
    const item = cartList[index];
    
    if (item.quantity > 1) {
      item.quantity -= 1;
      
      this.setData({
        cartList
      });
      
      this.calculateTotal();
      this.updateCartToGlobal();
    }
  },
  
  // 增加商品数量（与WXML绑定匹配）
  increaseQuantity: function (e) {
    this.increaseCount(e);
  },
  
  // 减少商品数量（与WXML绑定匹配）
  decreaseQuantity: function (e) {
    this.decreaseCount(e);
  },

  // 直接输入商品数量
  inputCount: function (e) {
    const { index } = e.currentTarget.dataset;
    const { cartList } = this.data;
    let quantity = parseInt(e.detail.value);
    
    if (isNaN(quantity) || quantity < 1) {
      quantity = 1;
    } else if (quantity > 99) {
      quantity = 99;
      wx.showToast({
        title: '已达到最大购买数量',
        icon: 'none'
      });
    }
    
    cartList[index].quantity = quantity;
    
    this.setData({
      cartList
    });
    
    this.calculateTotal();
    this.updateCartToGlobal();
  },

  // 删除商品
  deleteItem: function (e) {
    const { index } = e.currentTarget.dataset;
    
    wx.showModal({
      title: '提示',
      content: '确定要删除该商品吗？',
      success: (res) => {
        if (res.confirm) {
          const { cartList } = this.data;
          cartList.splice(index, 1);
          
          this.setData({
            cartList,
            isEmpty: cartList.length === 0
          });
          
          this.calculateTotal();
          // 直接使用更新后的allSelected状态，不再调用不存在的方法
          this.updateCartToGlobal();
          
          // 更新本地存储，防止页面重新加载时恢复
          wx.setStorageSync('cart', cartList);
          
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });
        }
      }
    });
  },

  // 删除商品（兼容removeItem bindtap）
  removeItem: function(e) {
    this.deleteItem(e);
  },

  // 更新购物车数据到全局变量
  updateCartToGlobal: function () {
    const { cartList } = this.data;
    app.globalData.cartList = cartList;
    
    // 更新本地存储，确保数据持久化
    wx.setStorageSync('cart', cartList);
    
    // 实际项目中应该同步到服务器
    // wx.cloud.callFunction({
    //   name: 'updateCart',
    //   data: {
    //     userId: app.globalData.userInfo._id,
    //     cartList
    //   }
    // }).catch(err => {
    //   console.error('同步购物车失败', err);
    // });
  },

  // 跳转到登录页面
  goToLogin: function () {
    console.log('Attempting to navigate to login page from cart');
    wx.reLaunch({
      url: '/pages/login/login',
      success: function() {
        console.log('Navigation to login page successful');
      },
      fail: function(error) {
        console.error('Failed to navigate to login page:', error);
      }
    });
  },

  // 跳转到首页
  goToHome: function () {
    wx.switchTab({
      url: '/pages/index/index'
    });
  },

  // 跳转到商品详情
  goToDetail: function (e) {
    const { id } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/product/product?id=${id}`
    });
  },

  // 去结算
  checkout: function () {
    const { cartList, selectedCount } = this.data;
    
    if (selectedCount === 0) {
      wx.showToast({
        title: '请选择要结算的商品',
        icon: 'none'
      });
      return;
    }
    
    // 过滤出选中的商品
    const selectedItems = cartList.filter(item => item.selected);
    
    console.log('结算商品:', selectedItems);
    
    // 保存到全局状态和本地存储，用于结算页面使用
    app.globalData.checkoutItems = selectedItems;
    wx.setStorageSync('checkoutItems', selectedItems);
    
    // 跳转到结算页面
    wx.navigateTo({
      url: '/pages/checkout/checkout?from=cart'
    });
  },

  // 兼容goToIndex
  goToIndex: function() {
    this.goToHome();
  }
}); 